package cn.zy.amyan.client.handler;

import cn.zy.amyan.client.AyClient;
import cn.zy.amyan.client.future.AyFutureResponse;
import cn.zy.amyan.core.base.RequestData;
import cn.zy.amyan.core.base.ResponseData;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 子言
 * @date 2024/5/1 下午 16:58
 */
public class ClientInvocationHandler implements InvocationHandler {
	private AyClient ayClient;
	/**
	 * 需要将AyClient传⼊，因为要基于此发送消息数据
	 *
	 * @param ayClient
	 */
	public ClientInvocationHandler(AyClient ayClient) {
		this.ayClient = ayClient;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		//获取类、⽅法、参数等信息
		String className = method.getDeclaringClass().getName();
		String methodName = method.getName();
		Class<?>[] parameterTypes = method.getParameterTypes();
		Object[] parameters = args;
		//封装请求对象
		RequestData request = new RequestData();
		request.setRequestId(UUID.randomUUID().toString());
		request.setClassName(className);
		request.setMethodName(methodName);
		request.setParameterTypes(parameterTypes);
		request.setParameters(parameters);
		//定义异步的响应对象
		AyFutureResponse futureResponse = new AyFutureResponse(request);
		//向服务端发送消息
		ayClient.sendMsg(request);
		//获取异步响应的消息
		ResponseData response = futureResponse.get(5, TimeUnit.SECONDS);
		if (response.getErrorMsg() != null) {
			throw new RuntimeException(response.getErrorMsg());
		}
		return response.getResult();
	}
}
